package guestbook;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
//import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.ReadPolicy;


@SuppressWarnings("serial")
public class GetData2 extends HttpServlet {
	//private static final Logger log = Logger.getLogger(SignGuestbookServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
	           throws ServletException,IOException {
		
		int timeframe = Integer.parseInt(req.getParameter("time"));

		resp.setContentType("text/plain");
		resp.setHeader("Cache-Control", "no-cache");
        
		PrintWriter o = resp.getWriter();
        
        String Sensors[] = { "SENSOR0", "SENSOR1" };
		String ValNames[] = { "Temp", "Dew", "Press" };
		String[][] DataStream = new String[Sensors.length][ValNames.length];
		for (int i=0; i < Sensors.length; i++) { //Output Streams inizialisieren
    		for (int j=0; j < ValNames.length; j++) {
				DataStream[i][j] = "function "+Sensors[i]+"_"+ValNames[j]+"() {\nreturn \"\" +\n";
    		}
		}
		
        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormatGmt.setTimeZone(TimeZone.getTimeZone("CET"));
        
        ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.EVENTUAL);
    	DatastoreServiceConfig eventuallyConsistentConfig = DatastoreServiceConfig.Builder.withReadPolicy(policy);
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(eventuallyConsistentConfig);

        Query q;
        int pageSize;
        if (timeframe == 1) {
        	q = new Query("SensorData");
        	pageSize = 1000;
        } else {
        	q = new Query("SensorName");
        	pageSize = 500;
        }

        q.addSort("date", Query.SortDirection.DESCENDING);
        PreparedQuery pq = datastore.prepare(q);
      
        for (Entity values : pq.asIterable(FetchOptions.Builder.withLimit(pageSize))) { //Daten einsortieren
        	//TODO: vielleicht kann man das noch generischer schreiben
        	//In der Art: ich schau mal rein was drin ist und dann ordne ich es zu.
        	//array.index und so
        	for (int i=0; i < Sensors.length; i++) {
        		for (int j=0; j < ValNames.length; j++) {
        			if ( values.getProperty("Sens").toString().compareTo(Sensors[i]) == 0 ) {       		
	        			if ( values.hasProperty(ValNames[j])) {
	        				DataStream[i][j] += "\""+  dateFormatGmt.format(values.getProperty("date")) + ", ";
	        				DataStream[i][j] += roundTwoDecimals((Double) values.getProperty(ValNames[j]));
	        				DataStream[i][j] += "\\n\" +\n";
	        			}
        			} else break;
        		}
        			
        	}
        }
        
        
    	for (int i=0; i < Sensors.length; i++) { // Daten sortiert ausgeben
    		for (int j=0; j < ValNames.length; j++) {
    			DataStream[i][j] += "\"\"; }";
    			o.println(DataStream[i][j]);
    			
    		}
    	}

        o.close();
	}
	
	double roundTwoDecimals(double d) {
	    return Math.round(d * 100.) /100.;
		}

}